const app = getApp()
const db = wx.cloud.database()
const _ = db.command
const $ = db.command.aggregate
const { showConfirm } = app.require("lib/modal")
const to = app.require("lib/awaitTo")

const { listData, loadData, refresh } = app.require("lib/loadList")
Page({
    data: {
        user: wx.getStorageSync('user'),
        type: "",
        post: listData
    },
    onLoad(e) {
        this.setData({ type: e.type })
        wx.setNavigationBarTitle({
            title: e.title,
        })
        this.getPost()
    },
    async getPost(loadType = "getData") {
        // 获取文章数据
        const matchMap = {
            myPost: { userId: this.data.user._id },
            myCollection: { collection: this.data.user._id }
        }
        const lastTime = this.data.post.lastTime
        const { getPost } = app.require("utils/request/post")
        const [err, res] = await to(getPost(matchMap[this.data.type], lastTime), "getPost")
        if (err) { return }
        loadData.call(this, {
            resData: res.list,
            targetObj: "post",
            loadType
        })
    },
    async showActionSheet() {
        const res = await wx.showActionSheet({
            itemList: ["编辑", "删除"],
        }).catch()
        switch (res.tapIndex) {
            case 0: {
                this.editPost()
                break
            }
            case 1: {
                this.deletePost()
            }
        }
        console.log(res.tapIndex)
    },
    async deletePost() {
        const res = await showConfirm("删除后无法恢复，确定要删除吗？")
        if (!res) return

    },
    onReachBottom() {
        // 触底加载
        if (this.data.post.nomore) return
        this.getPost()
    },
    async onPullDownRefresh() {
        // 下拉刷新
        refresh.call(this, "post")
        await this.getPost("refresh")
        wx.stopPullDownRefresh()
    }
})